/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component } from 'react';
import * as Sentry from '@sentry/browser';
import { Button, Intent, NonIdealState } from '@blueprintjs/core';
import { Icon } from 'antd';

// Layout
import Empty from '../Layout/Empty';

class ErrorBoundary extends Component {
  state = {
    hasError: false,
    eventId: null
  };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    Sentry.withScope(scope => {
      const eventId = Sentry.captureException(error);
      scope.setExtras(errorInfo);
      this.setState({ hasError: true, eventId });
    });
  }

  render() {
    const { hasError, eventId } = this.state;
    const btnSendReport = (
      <Button
        icon="envelope"
        text="Report Feedback"
        intent={Intent.DANGER}
        onClick={() => Sentry.showReportDialog({ eventId })}
      />
    );

    if (hasError) {
      // Render fallback UI
      return (
        <Empty showWaterMark>
          <div className="sku-page-empty-container">
            <NonIdealState
              icon={<Icon type="robot" />}
              title="We're sorry - something's gone wrong!"
              description="Our team has been notified, but click the button below to fill out a report."
              action={btnSendReport}
            />
          </div>
        </Empty>
      );
    }

    // When there's not an error, render children untouched
    return this.props.children;
  }
}

export default ErrorBoundary;
